package orc

import (
	"context"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	ocr_api20210707 "github.com/alibabacloud-go/ocr-api-20210707/client"
	util "github.com/alibabacloud-go/tea-utils/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/bitly/go-simplejson"
	"time"
)

type DriverLicense struct {
	Name          string
	Sex           string
	BirthDate     int64
	LicenseNumber string
}
type orc struct {
	AccessKeyId     string
	AccessKeySecret string
	client          *ocr_api20210707.Client
}

func NewOrc(AccessKeyId, AccessKeySecret, addr string) (*orc, error) {
	config := &openapi.Config{
		// 您的 AccessKey ID
		AccessKeyId: &AccessKeyId,
		// 您的 AccessKey Secret
		AccessKeySecret: &AccessKeySecret,
	}
	// 访问的域名
	config.Endpoint = tea.String(addr)
	//_result = &ocr_api20210707.Client{}
	client, err := ocr_api20210707.NewClient(config)
	if err != nil {
		return nil, err
	}

	return &orc{
		AccessKeyId:     AccessKeyId,
		AccessKeySecret: AccessKeySecret,
		client:          client,
	}, err
}

func (o *orc) DriverLicenseOcr(tx context.Context, url string) (*DriverLicense, error) {
	recognizeDrivingLicenseRequest := &ocr_api20210707.RecognizeDrivingLicenseRequest{
		Url: tea.String(url),
	}
	runtime := &util.RuntimeOptions{}
	res, err := o.client.RecognizeDrivingLicenseWithOptions(recognizeDrivingLicenseRequest, runtime)
	if err != nil {
		return nil, err
	}

	if res == nil {
		return nil, fmt.Errorf("orc res null")
	}

	if res.Body == nil {
		return nil, fmt.Errorf("orc res null")
	}

	jsonNew, err := simplejson.NewJson([]byte(res.Body.String()))

	if err != nil {
		return nil, fmt.Errorf("orc res Unmarshal err:%v", err)
	}
	jsonStr, err := jsonNew.Get("Data").String()
	if err != nil {
		return nil, fmt.Errorf("orc res Unmarshal err:%v", err)
	}
	jsonNew, err = simplejson.NewJson([]byte(jsonStr))
	if err != nil {
		return nil, fmt.Errorf("orc res Unmarshal err:%v", err)
	}

	data := jsonNew.Get("data").Get("face").Get("data")
	if data == nil {
		return nil, fmt.Errorf("orc res json get null")
	}

	name, _ := data.Get("name").String()
	sex, _ := data.Get("sex").String()
	birthDate, _ := data.Get("birthDate").String()
	licenseNumber, _ := data.Get("licenseNumber").String()
	timePar, _ := time.ParseInLocation("2006-01-02", birthDate, time.Local)
	return &DriverLicense{
		Name:          name,
		Sex:           sex,
		BirthDate:     timePar.Unix(),
		LicenseNumber: licenseNumber,
	}, nil
}
